package com.hxkcloud.patient.activitys;

import android.content.Intent;
import android.database.DataSetObserver;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hxkcloud.patient.R;
import com.hxkcloud.patient.YjhApplication;
import com.hxkcloud.patient.adapter.BetterPlanAdapter;
import com.hxkcloud.patient.beans.BetterPlanBean;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.patient.utils.BrightnessUtils;
import com.hxkcloud.patient.utils.ImageUtil;
import com.hxkcloud.patient.views.pulltorefreshlayout.PullToRefreshLayout;
import com.hxkcloud.patient.views.pulltorefreshlayout.PullableExpandableListView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by william_sun on 2016-11-29.
 * Description:患者康复方案列表
 */
public class PatientBetterPlanActivity extends BaseActivity implements PullToRefreshLayout.OnRefreshListener, BetterPlanAdapter.onBetterplanFunctionListener, View.OnClickListener {

    //title
    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;
    private ImageView iv_add;
    private TextView tv_add;

    private TextView tv_betterplan;

    private PullToRefreshLayout refreshLayout;
    private PullableExpandableListView eListView;

    private List<BetterPlanBean> dolists;
    private String patientId;//空的话是助手来的
    private BetterPlanAdapter adapter;

    //两个按钮
    private PopupWindow popup_easynotice;
    private TextView tv_easynotice_title;
    private TextView tv_easynotice_cancel;
    private TextView tv_easynotice_func;
    private int popType = 0;//0删除 1发送

    private BetterPlanBean planBean;//删除、修改、发送的单子

    private PopupWindow popup_add;//右上角操作框
    private LinearLayout ll_betterplan;
    private LinearLayout ll_scalelist;
    private LinearLayout ll_questionlist;

    private boolean isFuzhen = false;

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.PREGNANTBMIADD_BETTERPLANLIST_SUCCESS:
                dolists = (List<BetterPlanBean>) msg.obj;
                adapter.setDatas(dolists);
                refreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                if (isFuzhen) {
                    if (dolists.size() > 0) {
                        eListView.expandGroup(0);
                    }
                }
                break;
            case MessageCode.PREGNANTBMIADD_BETTERPLANLIST_FAILURE:
                if ((msg.obj != null) && (!TextUtils.isEmpty((String) msg.obj))) {
                    toastMsg((String) msg.obj);
                } else {
                    toastMsg(R.string.datagetfail);
                }
                refreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                break;
            case MessageCode.NETWORKCODE_DOORDERDELETE_SUCCESS:
                initData();
                break;
            case MessageCode.NETWORKCODE_DOORDERDELETE_FAILURE:
                if ((msg.obj != null) && (!TextUtils.isEmpty((String) msg.obj))) {
                    toastMsg((String) msg.obj);
                } else {
                    toastMsg(R.string.datadeletefail);
                }
                break;
            case MessageCode.NETWORKCODE_DOORDERUSE_SUCCESS:
                if ((msg.obj != null) && (!TextUtils.isEmpty((String) msg.obj))) {
                    toastMsg((String) msg.obj);
                } else {
                    toastMsg(R.string.datacommitsuccess);
                }
                break;
            case MessageCode.NETWORKCODE_DOORDERUSE_FAILURE:
                if ((msg.obj != null) && (!TextUtils.isEmpty((String) msg.obj))) {
                    toastMsg((String) msg.obj);
                } else {
                    toastMsg(R.string.datadeletefail);
                }
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patientbetterplan);

        patientId = getIntent().getStringExtra("patientId");
        isFuzhen = getIntent().getBooleanExtra("isFuzhen", false);
        dolists = new ArrayList<>();

        initView();
        initPopup();
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    @Override
    protected void initView() {
        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_back = (ImageView) findViewById(R.id.iv_title_back);
        tv_title = (TextView) findViewById(R.id.tv_title_title);
        iv_add = (ImageView) findViewById(R.id.iv_title_func);
        tv_add = (TextView) findViewById(R.id.tv_title_func);

        tv_betterplan = (TextView) findViewById(R.id.tv_betterplan);

        setTitlePadding(ll_title);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(this);
        if (TextUtils.isEmpty(patientId)) {
            tv_title.setText(getResources().getText(R.string.betterplan));
            tv_add.setVisibility(View.VISIBLE);
            tv_add.setText(R.string.performlist_text_create);
            tv_add.setOnClickListener(this);

            tv_betterplan.setVisibility(View.GONE);
        } else {
            tv_title.setText(getResources().getText(R.string.notice));
            iv_add.setVisibility(View.VISIBLE);
            iv_add.setImageResource(R.drawable.nav_add);
            iv_add.setOnClickListener(this);

            tv_betterplan.setVisibility(View.VISIBLE);
        }


        refreshLayout = (PullToRefreshLayout) findViewById(R.id.refreshlayout_betterplan);
        eListView = (PullableExpandableListView) findViewById(R.id.recyclerview_betterplan);

        refreshLayout.setOnRefreshListener(this);

        adapter = new BetterPlanAdapter(mContext, TextUtils.isEmpty(patientId) ? 1 : 0, dolists, this);
        adapter.registerDataSetObserver(observer);
        eListView.setAdapter(adapter);

        eListView.setGroupIndicator(null);
    }

    private DataSetObserver observer = new DataSetObserver() {
        @Override
        public void onChanged() {
            super.onChanged();
        }

        @Override
        public void onInvalidated() {
            super.onInvalidated();
        }
    };

    private void initPopup() {
        popup_easynotice = new PopupWindow(mContext);
        View viewNotice = LayoutInflater.from(mContext).inflate(R.layout.popup_easynotice, null);
        popup_easynotice.setContentView(viewNotice);

        popup_easynotice.setWidth((int) (screenWidth * 0.7));
        popup_easynotice.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup_easynotice.setFocusable(true);
        popup_easynotice.setTouchable(true);
        popup_easynotice.setOutsideTouchable(true);
        popup_easynotice.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popup_easynotice.setAnimationStyle(R.style.popupwindow_anim_alpha);

        tv_easynotice_title = (TextView) viewNotice.findViewById(R.id.tv_easynotice_title);
        tv_easynotice_cancel = (TextView) viewNotice.findViewById(R.id.tv_easynotice_cancel);
        tv_easynotice_func = (TextView) viewNotice.findViewById(R.id.tv_easynotice_func);

//        tv_easynotice_title.setText(R.string.suredeletethisitem);
        tv_easynotice_cancel.setOnClickListener(this);
        tv_easynotice_func.setOnClickListener(this);

        popup_easynotice.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                BrightnessUtils.lightOn(PatientBetterPlanActivity.this);
            }
        });

        popup_add = new PopupWindow(this);
        View viewAdd = LayoutInflater.from(mContext).inflate(R.layout.popup_betterplan_add, null);
        popup_add.setContentView(viewAdd);

        popup_add.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup_add.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup_add.setFocusable(true);
        popup_add.setTouchable(true);
        popup_add.setOutsideTouchable(true);
        popup_add.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popup_add.setAnimationStyle(R.style.popupwindow_anim_alpha);

        ll_betterplan = (LinearLayout) viewAdd.findViewById(R.id.ll_betterplan_betterplan);
        ll_scalelist = (LinearLayout) viewAdd.findViewById(R.id.ll_betterplan_scalelist);
        ll_questionlist = (LinearLayout) viewAdd.findViewById(R.id.ll_betterplan_questionlist);

        ll_betterplan.setOnClickListener(this);
        ll_scalelist.setOnClickListener(this);
        ll_questionlist.setOnClickListener(this);

        popup_add.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                BrightnessUtils.lightOn(PatientBetterPlanActivity.this);
            }
        });
    }

    public void expandFirstGroup() {
        if (dolists.size() > 0) {
            eListView.expandGroup(0);
        }
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {
        loading();
        YiJiaHuNetWorkUtils.betterPlanList(patientId, handler);
    }

    //列表刷新
    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        initData();
    }

    //列表加载更多
    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        refreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
    }


    //列表中的文章,文章标题和文章类别
    @Override
    public void article(String id) {
        Intent iArticle = new Intent(mContext, ArticleDetailActivity.class);
        iArticle.putExtra("articleId", id.split("aaaaa")[0]);
        if (id.contains("aaaaa")) {
            iArticle.putExtra("kindTitle", id.split("aaaaa")[1]);
        }
        iArticle.putExtra("acctType", YjhApplication.articlekind_course);
        startActivity(iArticle);
    }

    //列表删除
    @Override
    public void delete(int pIndex) {
        popType = 0;
        planBean = dolists.get(pIndex);
        tv_easynotice_title.setText(R.string.suredeletethisremind);
        popup_easynotice.showAtLocation(ll_title, Gravity.CENTER, 0, 0);
        BrightnessUtils.lightOff(PatientBetterPlanActivity.this);
    }

    //列表修改
    @Override
    public void modify(int pIndex) {
        Intent iEdit = new Intent(this, BetterPlanEditActivity.class);
        iEdit.putExtra("orderId", dolists.get(pIndex).getOrderId());
        iEdit.putExtra("patientId", patientId);
        iEdit.putExtra("isModify", true);
        startActivity(iEdit);
    }

    //列表点击发送，助手才有
    @Override
    public void send(int pIndex) {
        popType = 1;
        planBean = dolists.get(pIndex);
        tv_easynotice_title.setText(R.string.issendtouser);
        popup_easynotice.showAtLocation(ll_title, Gravity.CENTER, 0, 0);
        BrightnessUtils.lightOff(PatientBetterPlanActivity.this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back:
                finish();
                break;
            case R.id.iv_title_func://患者单子，新加康复计划、量表、调查问卷
                popup_add.showAsDropDown(iv_add, 0, ImageUtil.dip2px(10, mContext));
                BrightnessUtils.lightOff(PatientBetterPlanActivity.this);
                break;
            case R.id.tv_title_func://助手，新建康复计划
                Intent iPlan = new Intent(mContext, BetterPlanEditActivity.class);
                startActivity(iPlan);
                break;
            case R.id.tv_easynotice_cancel:
                popup_easynotice.dismiss();
                break;
            case R.id.tv_easynotice_func://popType  0删除 1发送
                popup_easynotice.dismiss();
                if (popType == 0) {
                    loading();
                    YiJiaHuNetWorkUtils.doOrderDelete(planBean.getOrderId(), handler);
                } else if (popType == 1) {
                    //选择用户
                    Intent iPatient = new Intent(mContext, ChooseUserActivity.class);
                    startActivityForResult(iPatient, 222);
                }
                break;
            case R.id.ll_betterplan_betterplan:
                popup_add.dismiss();
                Intent performIntent = new Intent(mContext, BetterPlanEditActivity.class);
                performIntent.putExtra("patientId", patientId);
                startActivity(performIntent);
                break;
            case R.id.ll_betterplan_scalelist:
                //跳入量表列表，然后给当前患者将要选择的量表
                popup_add.dismiss();
                Intent scaleIntent = new Intent(mContext, ScaleQuestionActivity.class);
                scaleIntent.putExtra("patientId", patientId);
                scaleIntent.putExtra("usefinish", true);
                startActivity(scaleIntent);
                break;
            case R.id.ll_betterplan_questionlist:
                //跳入调查问卷列表，然后给当前患者将要选择的调查问卷
                popup_add.dismiss();
                Intent questionIntent = new Intent(mContext, QuestionListActivity.class);
                questionIntent.putExtra("patientId", patientId);
                startActivity(questionIntent);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 222) {
                List<String> patients = data.getStringArrayListExtra("patients");
                loading();
                YiJiaHuNetWorkUtils.doOrderUse(patients, "", planBean.getOrderId(), handler);
            }
        }
    }
}
